package org.ourgrid.broker.commands.executors;

import org.ourgrid.broker.commands.SchedulerData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import br.edu.ufcg.lsd.commune.container.servicemanager.ServiceManager;
import br.edu.ufcg.lsd.commune.identification.ContainerID;
import br.edu.ufcg.lsd.commune.identification.DeploymentID;
import br.edu.ufcg.lsd.commune.processor.filetransfer.IncomingTransferHandle;
import br.edu.ufcg.lsd.commune.processor.filetransfer.OutgoingTransferHandle;

public class CancelTransferExecutor extends SchedulerCommandExecutor {

	private long handleId;
	private String localFileName;
	private String destinationFileName;
	private String description;
	private String id;
	private long fileSize;
	private boolean outgoing;
	
	/**
	 * 
	 * <CANCEL_TRANSFER handleId='long' fileName='String' description='String' id='String'
	 * fileSize='long' outgoing='boolean'/> 
	 * 
	 */
	public void execute(SchedulerData data, ServiceManager manager) {
		
		fillData(data.getXml());
		
		if (outgoing) {
			DeploymentID destinationID = new DeploymentID(id);
			
			OutgoingTransferHandle oHandle = 
				new OutgoingTransferHandle(handleId, localFileName, destinationFileName, description, 
						destinationID);
			
			manager.cancelOutgoingTransfer(oHandle);
			
		} else {
			
			ContainerID senderID = ContainerID.parse(id);
			
			IncomingTransferHandle iHandle = new IncomingTransferHandle(handleId, localFileName,
					fileSize, destinationFileName, description, senderID);
			
			manager.cancelIncomingTransfer(iHandle);
		}
	}
	
	private void fillData(String xml) {
		
		Document logDocFile = super.getXMl(xml);
		
		Element element = logDocFile.getDocumentElement();
		
		handleId = Long.valueOf(element.getAttribute("handleId"));
		localFileName = element.getAttribute("localFileName");
		destinationFileName = element.getAttribute("destinationFileName");
		description = element.getAttribute("description");
		id = element.getAttribute("id");
		fileSize = Long.valueOf(element.getAttribute("fileSize"));
		outgoing = Boolean.valueOf(element.getAttribute("outgoing"));
	}
}
